import json
import re


def outline_to_json(outline):
    """
    解析大纲
    :param outline:
    :return:
    """
    """
    {
  "title": "历史的意义与价值",
  "chapters": [
    {
      "chapter": "历史的重要性和作用",
      "slides": [
        {
          "slide": "为什么读历史",
          "sections": [
            {
              "section": "历史是远古以来人类活动的记载，包含成功经验与失败教训"
            },
            {
              "section": "历史中的悲欢离合、智慧与创造为我们提供启示"
            }
          ]
        },
        {
          "slide": "历史是共同记忆与灵魂所在",
          "sections": [
            {
              "section": "历史记载着逝去的人、物、事"
            }
          ]
        }
      ]
    },
    {
      "chapter": "历史的本质",
      "slides": [
        {
          "slide": "还原事实，揭示真相",
          "sections": [
            {
              "section": "历史的核心在于还原事实，基于真实的反思才有启发和智慧"
            }
          ]
        }
      ]
    }
  ]
}

    """
    lines = outline.split('\n')  # 按行拆分文本
    presentation = {"title": "", "chapters": []}
    current_chapter = None
    current_slide = None
    ppt_title_pattern = re.compile(r'^# (.*)')  # 主标题
    chapter_title_pattern = re.compile(r'^## (.*)')  # 章节标题
    slide_title_pattern = re.compile(r'^### (.*)')  # 单页标题`1 1`
    section_title_pattern = re.compile(r'^- (.*)')  # 小节标题

    for line in lines:
        line = re.sub(r"[\[\]]", "", line).strip()
        if not line:
            continue  # 跳过空行
        if ppt_title_pattern.match(line):
            # print("匹配到主标题")
            # print(ppt_title_pattern.match(line).group(1).strip())
            presentation['title'] = ppt_title_pattern.match(line).group(1).strip()
            continue
        if chapter_title_pattern.match(line):
            # print("匹配到章节标题")
            # print(chapter_title_pattern.match(line).group(1).strip())
            current_chapter = {"chapter": chapter_title_pattern.match(line).group(1).strip(), "slides": []}
            presentation['chapters'].append(current_chapter)
            continue
        if slide_title_pattern.match(line):
            # print("匹配到单页标题")
            # print(slide_title_pattern.match(line).group(1).strip())
            current_slide = {"slide": slide_title_pattern.match(line).group(1).strip(), "sections": []}
            current_chapter['slides'].append(current_slide)
            continue
        if section_title_pattern.match(line):
            # print("匹配到小节标题")
            # print(section_title_pattern.match(line).group(1).strip())
            current_section = {"section": section_title_pattern.match(line).group(1).strip()}
            current_slide['sections'].append(current_section)
            continue
    return json.dumps(presentation, ensure_ascii=False, indent=2)


def outline2md(outline):
    """
    将json格式大纲转换为 Markdown 格式
    :param outline: 传入的 JSON 大纲
    :return: 返回 Markdown 格式的大纲
    """
    outline = json.loads(outline)
    md_output = ""

    # 处理主标题
    if outline.get("title"):
        md_output += f"# {outline['title']}\n\n"

    # 遍历章节
    for chapter in outline.get("chapters", []):
        chapter_title = chapter.get("chapter")
        if chapter_title:
            md_output += f"## {chapter_title}\n\n"

        # 遍历幻灯片
        for slide in chapter.get("slides", []):
            slide_title = slide.get("slide")
            if slide_title:
                md_output += f"### {slide_title}\n\n"

            # 遍历小节
            for section in slide.get("sections", []):
                section_title = section.get("section")
                if section_title:
                    md_output += f"- {section_title}\n"

            # 添加小节后的空行
            md_output += "\n"

        # 章节后的空行
        md_output += "\n"

    return md_output


def chapter2md(chapter):
    """
    将json格式章节信息转换为md
    :param chapter:
    :return:
    """
    # print("input"+input)
    # chapter = json.loads(input)
    # print(chapter)
    # json.dumps(chapter, ensure_ascii=False, indent=2)
    md_output = ""

    # 遍历章节
    chapter_title = chapter.get("chapter")
    if chapter_title:
        md_output += f"## {chapter_title}\n\n"

    # 遍历幻灯片
    for slide in chapter.get("slides", []):
        slide_title = slide.get("slide")
        if slide_title:
            md_output += f"### {slide_title}\n\n"

        # 遍历小节
        for section in slide.get("sections", []):
            section_title = section.get("section")
            if section_title:
                md_output += f"- {section_title}\n"

        # 添加小节后的空行
        md_output += "\n"

    return md_output


def chapter2json(chapter):
    """
    解析单个章节
    :param chapter: 章节内容的字符串
    :return: 转换后的JSON格式数据
    """
    lines = chapter.split('\n')  # 按行拆分文本
    chapter_data = {"chapter": "", "slides": []}
    current_slide = None
    current_section = None
    ppt_title_pattern = re.compile(r'^## (.*)')  # 章节标题
    slide_title_pattern = re.compile(r'^### (.*)')  # 单页标题
    section_title_pattern = re.compile(r"^-\s+(.*)")  # 小节标题，匹配"- "后面的内容
    section_content_pattern = re.compile(r"^\s+-\s+(.*)")  # 小节内容，前面有缩进
    for line in lines:
        if not line:
            continue  # 跳过空行
        if ppt_title_pattern.match(line):
            chapter_data['chapter'] = ppt_title_pattern.match(line).group(1).strip()
            continue
        if slide_title_pattern.match(line):
            current_slide = {"slide": slide_title_pattern.match(line).group(1).strip(), "sections": []}
            chapter_data['slides'].append(current_slide)
            continue
        if section_title_pattern.match(line):
            section_title = section_title_pattern.match(line).group(1).strip()
            current_section = {"section": section_title, "section_content": ""}
            current_slide['sections'].append(current_section)
            continue
        if section_content_pattern.match(line):
            # 处理小节内容，前面有缩进
            section_content = section_content_pattern.match(line).group(1).strip()
            if current_section:
                current_section['section_content'] = section_content

    return json.dumps(chapter_data, ensure_ascii=False, indent=2)


# print(outline2json(text))
# print(outline2md(jsons))
# chapters = json.loads(outline2json(text))
# for chapter in chapters["chapters"]:
#     print(chapter2md(chapter))

